// 用户可以编辑文件  $HOME/.rand-reader.conf 改变发音命令，
// 默认值是:
// xfttsgo
// -stdin
// 第一行是命令，后面的各行是参数，内容从标准输入（STDIN）发送给命令
package main

import (
	"bytes"
	"flag"
	"io"
	"io/ioutil"
	"sync"

	"fyne.io/fyne/v2/dialog"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	//"golang.design/x/clipboard"
)

var server binding.String

func main() {
	var addr = flag.String("addr", "192.168.240.112", "指定tts_server地址")
	flag.Parse()
	server = binding.BindString(addr)
	createGui()
}

var mutex1 = sync.Mutex{}
var playing bool
var locked bool
var showBoard *widget.Entry
var btPauseOrContinue *widget.Button

func playString(s string) error {
	var err error
	txts := splitText(s)
	mutex1.TryLock()
	mutex1 = sync.Mutex{}
	playing = true
	btPauseOrContinue.SetText("暂停")
	for _, t := range txts {
		mutex1.Lock()
		locked = true
		showBoard.Append(t + "\n")
		showBoard.TypedKey(&fyne.KeyEvent{Name: fyne.KeyPageDown})
		addr, err := server.Get()
		if err != nil {
			return err
		}
		playText(t, addr)
		if playing && locked {
			mutex1.Unlock()
			locked = false
		}

	}
	playing = false
	return err
}

func createGui() {
	var text string

	var serverIP *widget.Entry

	//clipboard.Init()

	app := app.New()
	app.Settings().SetTheme(GetMyTheme())

	w := app.NewWindow("TTS-Reader with Android TTS Server")

	labelAbout := widget.NewLabel("播放剪贴板中的文字")
	serverIP = widget.NewEntryWithData(server)
	//serverBox := container.NewHBox(widget.NewLabel("服务器："), container.NewMax(serverIP))
	serverBox := widget.NewForm(widget.NewFormItem("服务器：", serverIP))

	btPlay := widget.NewButton("开始", func() {
		text = w.Clipboard().Content()
		showBoard.SetText("")
		go playString(text)
	})

	btFile := widget.NewButton("打开文件", func() {
		dialog.ShowFileOpen(func(uri1 fyne.URIReadCloser, err error) {
			if err != nil {
				return
			}
			buf := bytes.NewBufferString("")
			_, err = io.Copy(buf, uri1)
			if err != nil {
				return
			}
			text = buf.String()
			showBoard.SetText("")
			go playString(text)
		}, w)
	})

	btPauseOrContinue = widget.NewButton("暂停", func() {
		if playing {
			playing = false
			btPauseOrContinue.SetText("继续")
		} else {
			playing = true
			if locked {
				mutex1.Unlock()
				locked = false
			}

			btPauseOrContinue.SetText("暂停")
		}
	})

	showBoard = widget.NewEntry()
	showBoard.SetMinRowsVisible(20)
	showBoard.MultiLine = true
	boardScroll := container.NewVScroll(showBoard)
	boardScroll.SetMinSize(fyne.NewSize(800, 400))

	box1 := container.NewVBox(labelAbout, serverBox, container.NewGridWithRows(1, btPlay, btFile, btPauseOrContinue), boardScroll)

	w.SetContent(box1)

	w.SetOnDropped(func(p fyne.Position, uris []fyne.URI) {
		if len(uris) != 1 {
			showBoard.SetText("请确保只拖放一个文本文件。")
			return
		}
		path1 := uris[0].Path()
		data, err := ioutil.ReadFile(path1)
		if err != nil {
			showBoard.SetText(err.Error())
			return
		}
		showBoard.SetText("")
		go playString(string(data))
	})

	w.SetOnClosed(func() {
		app.Quit()
	})

	//w.Resize(fyne.Size{Width: 800, Height: 600})
	w.SetFixedSize(true)

	w.ShowAndRun()
}
